<template>
  <a-modal v-model:visible="props.show" title="编辑">
    <template #footer>
      <a-button key="back" @click="cancel">返回</a-button>
      <a-button key="submit" type="primary" @click="changeData">保存</a-button>
    </template>
    <a-form layout="inline">
      <FormInput label="商品名称" type="text" v-model:value="data.title" />
      <FormInput label="价格" type="number" v-model:value="data.price" />
      <FormSelect label="分类" :data-list="categoryList" v-model:value="data.category" />
      <a-upload v-model:file-list="fileList" name="avatar" list-type="picture-card" style="width: 200px; height: 200px" :show-upload-list="false" :action="beforeUpload" :beforeUpload="beforeUpload">
        <a-image v-if="data.coverImg" :width="200" :preview="false" :src="data.coverImg"></a-image>
        <div v-else>
          <div class="ant-upload-text">Upload</div>
        </div>
      </a-upload>
    </a-form>
  </a-modal>
</template>
<script setup lang="ts">
import { defineEmits, reactive, ref, watch } from "vue";
import FormInput from "@/components/FormInput/FormInput.vue";
import FormSelect from "@/components/FormSelect/FormSelect.vue";
import { EnumToDicData } from "@/entity/helper/enum.helper";
import { Config, EventBus, Service } from "@/main";
import Product from "@/entity/interface/product.interface";
import { showAlert } from "@/entity/helper/tips.helper";
import { UploadChangeParam } from "ant-design-vue";
const emit = defineEmits(["update:show", "update:finish"]);
const props = defineProps<{
  data: Product;
  categoryList: Array<{ label: string; value: number }>;
  show: boolean;
}>();
const data = reactive(props.data);
const changeData = () => {
  if (data.id === null) {
    //post创建
    Service.Shop.addProduct(data).then(res => {
      EventBus.emit(Config.Event.refreshProductList);
      emit("update:show", false);
      showAlert("创建成功", "SUCCESS");
    });
  } else {
    //put修改
    Service.Shop.changeProduct(data).then(res => {
      EventBus.emit(Config.Event.refreshProductList);
      emit("update:show", false);
      showAlert("修改成功", "SUCCESS");
    });
  }
};
const cancel = () => {
  emit("update:show", false);
};
const fileList = ref([]);
function getBase64(img: Blob, callback: (base64Url: string) => void) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result as string));
  reader.readAsDataURL(img);
}
const beforeUpload = (file: any) => {
  getBase64(file, (base64Url: string) => {
    data.coverImg = base64Url;
  });
  return false;
};
</script>
